import csv

import requests
from bs4 import BeautifulSoup

"""
目标：抓取豆瓣电影Top 250榜单的电影标题和评分。
步骤：
1.发送请求：使用Requests获取网页HTML内容。
2.解析内容：使用BeautifulSoup提取电影标题和评分。
3.存储数据：将抓取到的数据保存到CSV文件。
"""


def test():
    #
    url = "https://movie.douban.com/top250"
    headers = {"User-Agent": "Mozilla/5.0"}
    response = requests.get(url, headers=headers)

    #
    soup = BeautifulSoup(response.text, 'html.parser')
    movies = []
    for item in soup.find_all('div', class_='item'):
        title = item.find('span', class_='title').text
        rating = item.find('span', class_='rating_num').text
        people = item.find("div", class_="star").find_all("span")[-1].get_text()
        print(people)
        movies.append([title, rating])

    #
    with open("douban_top250.csv", mode="w", encoding="utf-8", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["Title", "Rating"])
        writer.writerows(movies)
